package cc.eddic.examinationsystem.web;


import cc.eddic.examinationsystem.Role;
import cc.eddic.examinationsystem.core.BaseController;
import cc.eddic.examinationsystem.domain.Exam;
import cc.eddic.examinationsystem.domain.ExamStudent;
import cc.eddic.examinationsystem.domain.Student;
import cc.eddic.examinationsystem.dto.ExamModel;
import cc.eddic.examinationsystem.dto.StudentModel;
import cc.eddic.examinationsystem.repository.ExamRepository;
import cc.eddic.examinationsystem.repository.ExamStudentRepository;
import cc.eddic.examinationsystem.repository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/exam_student")
public class ExamStudentController  extends BaseController {

    public ExamStudentController(ExamStudentRepository examStudentRepository) {
        this.examStudentRepository = examStudentRepository;
    }

    //考生管理系统首页(主页面)：显示考生库
    @GetMapping("/students")
    public String studentList(Model model) {
        //放在请求域中
        model.addAttribute("studentModels", studentRepository.findAll().stream().map(StudentModel::from).collect(Collectors.toList()));
        return "student-management-Tyq";
    }

    //根据输入的考试信息查询exam_student_info信息
    @GetMapping("/exam_select")
    public String examSelect(Model model) {
        model.addAttribute("examModels", examRepository.findAll().stream().map(ExamModel::from).collect(Collectors.toList()));
        return "exam-find-Tyq";
    }

    @GetMapping("/exam_find")
    public String examStudentList(Model model, @ModelAttribute("exam") List<String> exam) {
        long examId = Long.parseLong(exam.get(0));
        //通过ExamID找到Exam,并创建ExamModel传入前端
        //日期格式转化LocalDateTime转到String后 根据Exam创建ExamModel
        Exam exam1 = examRepository.findById(examId).orElseThrow(NoSuchFieldError::new);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库的时间“2022-02-09 10:21”，转化为前端需要的字符串格式的时间“2022-02-09T10:21”
        String startTtime = df.format(exam1.getExamAt());
        ExamModel examModel = new ExamModel(exam1.getId(), exam1.getName(), startTtime, exam1.getTimeLimit(), exam1.getTotalScore(), exam1.getVersion());
        //通过examID找到ExamStudent中的Student
        List<StudentModel> studentModels = examStudentRepository.findAll().stream().filter(examStudent -> examStudent.getExam().getId().equals(examModel.getId())).map(examStudent -> {
            Student student = examStudent.getStudent();
            return StudentModel.from(student);
        }).collect(Collectors.toList());
        model.addAttribute("examModel", examModel);
        model.addAttribute("studentModels", studentModels);
        model.addAttribute("success", "null");
        return "exam-student-info-Tyq";
    }

    //已使用studentModel
    //跳转到：通过考生库添加考生页面
    @GetMapping("/add")
    public String add(Model model) {
//        model.addAttribute("dt", LocalDateTime.now());
        model.addAttribute("studentModels", studentRepository.findAll().stream().map(StudentModel::from).collect(Collectors.toList()));
        model.addAttribute("examModels", examRepository.findAll().stream().map(ExamModel::from).collect(Collectors.toList()));
        return "student-add-Tyq";
    }

    //从考生库添加考生页面 真正添加exam_student
    //Spring MVC自动将请求参数和对象属性一一绑定，要求属性名一致
    @PostMapping(value = "/add", params = "save")
    public String examStudentAdd(Model model, String checkBox, @ModelAttribute("exam") List<String> examIn) {
        if (checkBox == null) {
            if (log.isDebugEnabled()) log.debug("没有选择任何复选框");
            model.addAttribute("studentModels", studentRepository.findAll().stream().map(StudentModel::from).collect(Collectors.toList()));
            model.addAttribute("examModels", examRepository.findAll().stream().map(ExamModel::from).collect(Collectors.toList()));
            model.addAttribute("tip", "您未选择要添加的考生");
            return "student-add-Tyq";
        }
        //获取下拉列表选择的exam的ID
        long examId = Long.parseLong(examIn.get(0));
        Exam exam = examRepository.findById(examId).orElseThrow(NoSuchFieldError::new);
        if (log.isDebugEnabled())
            log.debug("选择的考试信息为：{}", examRepository.findById(examId).orElseThrow(NoSuchFieldError::new).toString());
        //将复选框返回的字符串分割，获取到复选框选择的选项 所对应的exam_student的Id
        List<String> studentModelId = Arrays.asList(checkBox.split(","));
        //通的
        //对于已经存在的examStudent打印出已经存在的信息
        //对于其他的examStudent正常添加
        //计数，看有没有examStudent添加成功
        int count = 0;
        for (String s : studentModelId) {
            //通过Student和Exam 创建ExamModel对象
            ExamStudent examStudent = new ExamStudent(studentRepository.findById(Long.parseLong(s)).orElseThrow(NoSuchFieldError::new), exam);
            if (examStudentRepository.findAll().stream().anyMatch(examStudent1 -> examCompare(examStudent.getExam(), examStudent1.getExam()) && studentCompare(examStudent.getStudent(), examStudent1.getStudent()))) {
                if (log.isDebugEnabled()) log.debug("这个考生已存在：{}", examStudent);
            } else {
                if (log.isDebugEnabled())
                    log.debug("加入本场考试的考生信息为：{}", studentRepository.findById(Long.parseLong(s)).orElseThrow(NoSuchFieldError::new).toString());
                examStudentRepository.save(examStudent);
                count++;
                if (log.isDebugEnabled()) log.debug("ID为{}的考生已添加成功", s);
            }
        }
        if (count == 0) {
            //复选框中的考生均已存在
            model.addAttribute("success", "考生均已存在!");
        } else {
            //有人被添加成功了
            model.addAttribute("success", "添加成功");
        }
        //把 当前考试 和 参加考试的考生 返回到添加成功页面
        model.addAttribute("examModel", ExamModel.from(exam));
        model.addAttribute("studentModels", examStudentRepository.findAll().stream().filter(examStudent1 -> examCompare(examStudent1.getExam(), exam)).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
        return "exam-student-info-Tyq";
    }

    //跳转到通过工号搜索考生页面
    @GetMapping("/find")
    public String findAdd(Model model) {
        model.addAttribute("examStudentList", examStudentRepository.findAll());
        model.addAttribute("tip","null");
        return "student-find-Tyq";
    }

    //根据输入工号从考生库查找考生
    @GetMapping(value = "/find_add")
    public String findStudentFromStudent(Model model, @RequestParam String text) {
        if(text.length()==0){
            model.addAttribute("tip", "您还未输入员工号！");
            //返回输入员工号查找考生页面
            return "student-find-Tyq";
        }
        if (!studentRepository.findAll().stream().map(Student::getEmployeeNo).collect(Collectors.toList()).contains(Long.parseLong(text))) {
            System.out.println("****** 员工号不存在！*****");
            model.addAttribute("tip", "您查找的员工不存在！");
            //返回输入员工号查找考生页面
            return "student-find-Tyq";
        }
        if (log.isDebugEnabled()) log.debug("要查找的员工号为: {}", text);
        model.addAttribute("studentModel", StudentModel.from(studentRepository.findAll().stream().filter(student -> student.getEmployeeNo() == Long.parseLong(text)).findFirst().orElseThrow(NoSuchFieldError::new)));
        model.addAttribute("examModels", examRepository.findAll().stream().map(ExamModel::from).collect(Collectors.toList()));
        return "student-find-add-Tyq";
    }

    //通过搜索到的考生信息 添加到本场考试的页面 真正添加exam_student
    @PostMapping(value = "/find_add", params = "save")
    public String addStudentToExamStudent(Model model, @ModelAttribute StudentModel studentModel, @ModelAttribute("exam") List<String> examIn) {
        //获取下拉列表选择的考试的ID
        long examId = Long.parseLong(examIn.get(0));
        //通过Exam和Student创建ExamStudent
        //*****注意：exam和student必须是examRepository和studentRepository中找到的，而不是studentModel转变的或是自己创建的。
        Exam exam = examRepository.findById(examId).orElseThrow(NoSuchFieldError::new);
        Student student = studentRepository.findAll().stream().filter(student1 -> studentCompare(studentModelToStudent(studentModel), student1)).collect(Collectors.toList()).get(0);
        ExamStudent examStudent = new ExamStudent(student, exam);
        //通的
        //对于已经存在的examStudent打印出已经存在的信息
        //对于其他的examStudent正常添加
        if (examStudentRepository.findAll().stream().anyMatch(examStudent1 -> examCompare(examStudent.getExam(), examStudent1.getExam()) && studentCompare(examStudent.getStudent(), examStudent1.getStudent()))) {
            if (log.isDebugEnabled()) log.debug("考生已存在：{}", examStudent);
            model.addAttribute("examModel", ExamModel.from(exam));
            model.addAttribute("studentModels", examStudentRepository.findAll().stream().filter(examStudent1 -> examCompare(examStudent1.getExam(), exam)).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
            model.addAttribute("success", "考生已存在！");
            return "exam-student-info-Tyq";
        } else {
            if (log.isDebugEnabled())
                log.debug("加入本场考试的考生信息为：{}", studentRepository.findById(studentModel.getId()).orElseThrow(NoSuchFieldError::new).toString());
            examStudentRepository.save(examStudent);
            if (log.isDebugEnabled()) log.debug("ID为{}的考生已添加成功", studentModel.getId());
            //把 当前考试 和 参加考试的考生 返回到添加成功页面
            model.addAttribute("examModel", ExamModel.from(exam));
            model.addAttribute("studentModels", examStudentRepository.findAll().stream().filter(examStudent1 -> examCompare(examStudent1.getExam(), exam)).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
            model.addAttribute("success", "添加成功！");
            return "exam-student-info-Tyq";
        }
    }

    //进入student-input-add页面
    @GetMapping("/input")
    public String studentInput(Model model) {
        model.addAttribute("examModels", examRepository.findAll());
        model.addAttribute("studentModel", StudentModel.builder().build());
        return "student-input-add-Tyq";
    }

    //暂时不实现此功能
    //根据student-input-add页面选择的examId和输入的student信息 将student添加到examStudent
    @PostMapping("/input_add")
    public String studentInputAdd(Model model, @ModelAttribute StudentModel studentModel, @RequestParam List<String> exam, @RequestParam List<String> gender) {
//        if(log.isDebugEnabled()) log.debug("从页面获取的员工号为{}",studentModel.getEmployeeNo());
//        if(log.isDebugEnabled()) log.debug("从页面获取的examID为{}",examIn.get(0));
//        if(log.isDebugEnabled()) log.debug("从页面获取的gender为{}",gender.get(0));
//        long examId=Long.parseLong(examIn.get(0));
//        //把下拉列表选择的gender赋值给studentModel
//        studentModel.setGender(Integer.parseInt(gender.get(0)));
//        //创建Exam和Student -> examStudent
//        Exam exam=examRepository.findById(examId).orElseThrow(NoSuchFieldError::new);
//        Student student=studentRepository.findAll().stream().filter(student1 -> studentCompare(student1,studentModelToStudent(studentModel))).collect(Collectors.toList()).get(0);
////        Student student=new Student(studentModel.getEmployeeNo(),studentModel.getName(),studentModel.getGender(),studentModel.getEmail(),studentModel.getMobile());
//        ExamStudent examStudent=new ExamStudent(student,exam);
//        if(examStudentRepository.findAll().stream().anyMatch(examStudent1 -> examCompare(examStudent.getExam(), examStudent1.getExam()) && studentCompare(examStudent.getStudent(), examStudent1.getStudent()))){
//            model.addAttribute("examModel",examRepository.findById(examId).orElseThrow(NoSuchFieldError::new));
//            model.addAttribute("studentModels",examStudentRepository.findAll().stream().filter(examStudent1 -> examStudent1.getExam().getId().equals(examId)).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
//            model.addAttribute("success","考生已存在！");
//            return "exam-student-info-Tyq";
//        }else {
//            //存入数据库
//            examStudentRepository.save(examStudent);
//            model.addAttribute("examModel", examRepository.findById(examId).orElseThrow(NoSuchFieldError::new));
//            model.addAttribute("studentModels", examStudentRepository.findAll().stream().filter(examStudent1 -> examStudent1.getExam().getId().equals(examId)).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
//            model.addAttribute("success", "添加成功！");
//            return "exam-student-info-Tyq";
//        }
        model.addAttribute("tip", "系统正在升级中......");
        return "student-input-add-Tyq";
    }

    //exam-student-info页面的删除功能 点击删除按钮时 删除按钮对应那一行的examId和studentId传到/del功能中
    //根据examId和studentId移除examStudent
    @PostMapping("/del")
    public String examStudentDel(Model model, @RequestParam("studentId") String studentId, @RequestParam("examId") String examId) {
        if (log.isDebugEnabled()) log.debug("要删除的考生的examID为{}", examId);
        if (log.isDebugEnabled()) log.debug("要删除的考生的studentID为{}", studentId);
        long examID = Long.parseLong(examId);
        long studentID = Long.parseLong(studentId);
        examStudentRepository.deleteAll(examStudentRepository.findAll().stream().filter(examStudent -> examStudent.getStudent().getId().equals(studentID) && examStudent.getExam().getId().equals(examID)).collect(Collectors.toList()));
        if (log.isDebugEnabled()) log.debug("考生已从本场考试移除");
        //把 当前考试 和 参加考试的考生 返回到添加成功页面
        model.addAttribute("examModel", ExamModel.from(examRepository.findById(examID).orElseThrow(NoSuchFieldError::new)));
        model.addAttribute("studentModels", examStudentRepository.findAll().stream().filter(examStudent1 -> examCompare(examStudent1.getExam(), examRepository.findById(examID).orElseThrow(NoSuchFieldError::new))).map(examStudent1 -> StudentModel.from(examStudent1.getStudent())).collect(Collectors.toList()));
        model.addAttribute("success", "删除成功！");
        return "exam-student-info-Tyq";
    }

    private Student studentModelToStudent(StudentModel studentModel) {
        return new Student(studentModel.getEmployeeNo(), studentModel.getName(), studentModel.getGender(), studentModel.getEmail(), studentModel.getMobile(),studentModel.getPassword(), Role.EXAMINEE);
    }

    private boolean examCompare(Exam exam1, Exam exam2) {
        return exam1.getName().equals(exam2.getName()) && exam1.getExamAt().equals(exam2.getExamAt()) && exam1.getTimeLimit().equals(exam2.getTimeLimit()) && exam1.getTotalScore().equals(exam2.getTotalScore());
    }

    private boolean studentCompare(Student student1, Student student2) {
        return student1.getEmployeeNo().equals(student2.getEmployeeNo()) && student1.getName().equals(student2.getName()) && student1.getGender().equals(student2.getGender()) && student1.getEmail().equals(student2.getEmail()) && student1.getMobile().equals(student2.getMobile());
    }

    //依赖注入
    @Autowired
    private StudentRepository studentRepository;
    //依赖注入
    @Autowired
    private ExamRepository examRepository;

    private final ExamStudentRepository examStudentRepository;
}
